<?php

namespace App\Models;

// use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel as Model;
use DB;

class MemberAddress extends Model
{
    //
    protected $primaryKey = 'id';

    protected $casts = [
        'created_at' => 'Y-m-d H:i:s',
        'updated_at' => 'Y-m-d H:i:s',
    ];

    protected $visible = ['id', 'member_id','consignee','mobile','country','province','city','district','address','default','province_name', 'city_name', 'district_name', 'created_at', 'updated_at'];

    protected $fillable = ['id', 'member_id','consignee','mobile','country','province','city','district','address','default','province_name', 'city_name', 'district_name', 'created_at', 'updated_at'];

    protected $guarded = ['province_name', 'city_name', 'district_name'];

    /**
     * 会员信息
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function member()
    {
        return $this->belongsTo(Member::class, 'member_id');
    }

    public function getProvinceNameAttribute()
    {
        $province_name = '';

        if (isset($this->attributes['province']) && $this->attributes['province'])
        {
            $region = Region::where('code', $this->attributes['province'])->first();

            if (isset($region->name))
            {
                $province_name = $region->name;
            }
        }

        return $province_name;
    }

    public function getCityNameAttribute()
    {
        $city_name = '';

        if (isset($this->attributes['city']) && $this->attributes['city'])
        {
            $region = Region::where('code', $this->attributes['city'])->first();

            if (isset($region->name))
            {
                $city_name = $region->name;
            }
        }

        return $city_name;
    }

    public function getDistrictNameAttribute()
    {
        $district_name = '';

        if (isset($this->attributes['district']) && $this->attributes['district'])
        {
            $region = Region::where('code', $this->attributes['district'])->first();

            if (isset($region->name))
            {
                $district_name = $region->name;
            }
        }

        return $district_name;
    }

    public static function getList(array $attributes)
    {
        extract($attributes);

        $where = ['member_id' => $member_id];

        $model = MemberAddress::where($where);

        $total = $model->count();

        $model->orderBy('default', 'DESC')->orderBy('updated_at', 'DESC');

        if (isset($per_page))
        {
            $data = $model->paginate($per_page)->toArray();
            // dd($data);
            foreach ((array)$data['data'] as $key=>$val)
            {
                if (!$val) continue;

                $province_name = '';
                if (isset($val['province']) && $val['province'])
                {
                    $region = Region::where('code', $val['province'])->first();

                    if (isset($region->name))
                    {
                        $province_name = $region->name;
                    }
                }
                $data['data'][$key]['province_name'] = $province_name;

                $city_name = '';
                if (isset($val['city']) && $val['city'])
                {
                    $region = Region::where('code', $val['city'])->first();

                    if (isset($region->name))
                    {
                        $city_name = $region->name;
                    }
                }
                $data['data'][$key]['city_name'] = $city_name;

                $district_name = '';
                if (isset($val['district']) && $val['district'])
                {
                    $region = Region::where('code', $val['district'])->first();

                    if (isset($region->name))
                    {
                        $district_name = $region->name;
                    }
                }
                $data['data'][$key]['district_name'] = $district_name;

            }
            return self::formatBody(['list' => $data['data'], 'paged' => self::formatPaged($page, $per_page, $total)]);
        }
        else
        {
            $data = $model->get()->toArray();

            foreach ($data as $key=>$val)
            {
                if (!$val) continue;

                $province_name = '';
                if (isset($val['province']) && $val['province'])
                {
                    $region = Region::where('code', $val['province'])->first();

                    if (isset($region->name))
                    {
                        $province_name = $region->name;
                    }
                }
                $data[$key]['province_name'] = $province_name;

                $city_name = '';
                if (isset($val['city']) && $val['city'])
                {
                    $region = Region::where('code', $val['city'])->first();

                    if (isset($region->name))
                    {
                        $city_name = $region->name;
                    }
                }
                $data[$key]['city_name'] = $city_name;

                $district_name = '';
                if (isset($val['district']) && $val['district'])
                {
                    $region = Region::where('code', $val['district'])->first();

                    if (isset($region->name))
                    {
                        $district_name = $region->name;
                    }
                }
                $data[$key]['district_name'] = $district_name;
            }

            return self::formatBody(['list' => $data]);
        }
    }

    public static function updateOrCreateAddress(array $attributes, &$msg)
    {
        extract($attributes);

        DB::beginTransaction();

        // 此处应该走事务
        try {

            $params = [
                'member_id' => $member_id,
                'consignee' => trim($consignee),
                'mobile' => trim($mobile),
                'province' => trim($province),
                'city' => trim($city),
                'district' => trim($district),
                'address' => trim($address),
                'default' => $default ? 1 : 0,
            ];
            // dd($params);
            if ($params['default']==1)
            {
                MemberAddress::where('member_id', $member_id)->update(['default'=>0]);
            }

            if (isset($id) && $id)
            {
                $res = MemberAddress::where('id', $id)->update($params);
                if ($res)
                {
                    $res =  MemberAddress::where('id', $id)->first();
                }
            }
            else
            {
                $res = MemberAddress::create($params);
            }

            DB::commit();

        } catch (\Exception $exception) {

            DB::rollback();
            $msg = '收货地址保存失败:'.$exception->getMessage();
            return false;
            // return self::formatError(400 , '收货地址保存失败:'.$exception->getMessage());
        }

        return $res;
    }

    public static function deleteAddress(array $attributes, &$msg)
    {
        extract($attributes);

        DB::beginTransaction();

        try {

            $res = MemberAddress::where('id', $id)->where('member_id', $member_id)->delete();

            DB::commit();

        } catch (\Exception $exception) {

            DB::rollback();

            $msg = '删除收货地址失败:'.$exception->getMessage();
            return false;
            // return self::formatError(400 , '删除收货地址失败:'.$exception->getMessage());
        }

        return $res;
    }


}
